# coding=utf-8
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny, IsAuthenticated

import settings
from social.account.serializers import *
from social.im.token04 import generate_token04
from social.utils.oss import OssSystem
from social.utils.sms import SMSAuth
from social.utils.views import *


class AccountViewSet(BaseGenericViewSet, CreateModelMixin, UpdateModelMixin):
    permission_classes = (AllowAny,)
    serializer_class = UserUpdateSerializer
    queryset = User.objects.all()

    @action(methods=['Post'], detail=False, serializer_class=UserLoginSerializer)
    def login(self, request, *args, **kwargs):
        return super(AccountViewSet, self).create(request, *args, **kwargs)

    @action(methods=['POST'], detail=False)
    def send_code(self, request, *args, **kwargs):
        phone = request.data.get('phone')
        usage = request.data.get("usage", SMSAuth.LOGIN)
        sms_auth = SMSAuth(usage=usage)
        if request.ua.other.channel != 'admin':
            sms_auth.send_auth_code(phone)
        return Response()

    @action(methods=['POST'], detail=False, serializer_class=UserUpdateSerializer,
            permission_classes=(IsAuthenticated,))
    def edit(self, request, *args, **kwargs):
        self.kwargs['pk'] = self.request.user.id
        return super(AccountViewSet, self).update(request, *args, **kwargs)

    @action(methods=['PUT'], detail=False)
    def set_password(self, request, *args, **kwargs):
        user = request.user
        password = request.data.get('password')
        user.set_password(password)
        user.save()
        return Response()

    @action(methods=['POST'], detail=False, permission_classes=(IsAuthenticated,))
    def im_token(self, request, *args, **kwargs, ):
        token = generate_token04(settings.ZEGO_APP_ID, request.user.im_id, settings.ZEGO_APP_SECRET, 3600, '')
        return Response(data={'im_token': token.token, 'im_id': request.user.im_id})
